package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.config.PageInfo;
import cn.wolfcode.rbac.exception.CustomException;
import cn.wolfcode.rbac.mapper.*;
import cn.wolfcode.rbac.model.DepartmentDO;
import cn.wolfcode.rbac.model.EmployeeDO;
import cn.wolfcode.rbac.model.EmployeeRoleDO;
import cn.wolfcode.rbac.model.RoleDO;
import cn.wolfcode.rbac.request.EmployeeQueryRequest;
import cn.wolfcode.rbac.request.EmployeeRequest;
import cn.wolfcode.rbac.service.EmployeeService;
import cn.wolfcode.rbac.vo.DepartmentVO;
import cn.wolfcode.rbac.vo.EmployeeQueryVO;
import cn.wolfcode.rbac.vo.EmployeeVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Lu.F
 * @version 1.0
 * @Description TODO
 * @date 2022/5/19 15:53
 */
@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private EmployeeRoleMapper employeeRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 分页查询用户信息
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<EmployeeVO> listEmployee(int page, int size) {
        Page<EmployeeDO> pageInfo = new Page<>(page, size);
        IPage<EmployeeDO> employeeDOIPage = employeeMapper.selectPage(pageInfo, null);
        /*
        Map<String, Object> map = new HashMap<>(3);
        map.put("total_page", employeeDOIPage.getPages());
        map.put("total_records", employeeDOIPage.getTotal());
        map.put("current_data", employeeDOIPage.getRecords());
        */
        PageInfo<EmployeeVO> doPageInfo = new PageInfo<>();
        doPageInfo.setPage(page);
        doPageInfo.setTotalPage(employeeDOIPage.getPages());
        doPageInfo.setSize(size);
        doPageInfo.setTotalRecords(employeeDOIPage.getTotal());
        doPageInfo.setCurrentData(employeeDOIPage.getRecords().stream().map(obj->{
            EmployeeVO employeeVO = new EmployeeVO();
            BeanUtils.copyProperties(obj,employeeVO);
            DepartmentDO departmentDO = departmentMapper.selectOne(new QueryWrapper<DepartmentDO>().eq("id", obj.getDeptId()));
            employeeVO.setDepartmentDO(departmentDO);
            return employeeVO;
        }).collect(Collectors.toList()));
        return doPageInfo;
    }


    /**
     * 更新或者保存员工
     *
     * @param employeeRequest
     * @return
     */
    @Override
    public void saveOrUpdate(EmployeeRequest employeeRequest, Long[] roleIds) {

        Long empId = employeeRequest.getId();
        // 查找数据库是否存在该对象
        EmployeeDO employeeDO = employeeMapper.selectOne(new QueryWrapper<EmployeeDO>().eq("id", empId));

        // 复制对象
        EmployeeDO employeeDO1 = new EmployeeDO();
        BeanUtils.copyProperties(employeeRequest, employeeDO1);
        // 不存在则插入
        if (null == employeeDO) {
            employeeMapper.insert(employeeDO1);
        } else {
            employeeMapper.update(employeeDO1, new QueryWrapper<EmployeeDO>().eq("id", empId));
        }


        // 删除用户原本的权限
        employeeRoleMapper.delete(new QueryWrapper<EmployeeRoleDO>().eq("employee_id", empId));

        if(empId == null){
            EmployeeDO employeeDO2 = employeeMapper.selectOne(new QueryWrapper<EmployeeDO>().eq("name",employeeRequest.getName()));
            empId = employeeDO2.getId();
        }

        if (roleIds != null && roleIds.length != 0) {
            // 存在则更新
            employeeRoleMapper.insertEmpRole(empId, roleIds);
        }


    }

    /**
     * 获取信息
     *
     * @param id
     * @return
     */
    @Override
    public EmployeeDO get(Long id) {
        return employeeMapper.selectOne(new QueryWrapper<EmployeeDO>().eq("id", id));
    }

    /**
     * 删除员工信息
     *
     * @param id
     * @return
     */
    @Override
    public void delete(Long id) {
        // 删除用户权限
        employeeRoleMapper.delete(new QueryWrapper<EmployeeRoleDO>().eq("employee_id",id));
        // 删除用户
        employeeMapper.delete(new QueryWrapper<EmployeeDO>().eq("id", id));
    }


    /**
     * 高级查询员工信息
     *
     * @param employeeQueryRequest
     * @return
     */
    @Override
    public PageInfo<EmployeeQueryVO> list(int page, int size, EmployeeQueryRequest employeeQueryRequest) {
        // 根据高级查找员工对象
//        Map<String, Object> map = new HashMap<>(3);
        PageInfo<EmployeeQueryVO> voPageInfo = new PageInfo<>();
        List<EmployeeDO> employeeDOS = employeeMapper.selectEmployee(employeeQueryRequest.getKeyword(), employeeQueryRequest.getDeptId());
        if (employeeDOS != null) {
            // 转换
            List<EmployeeQueryVO> employeeQueryVOS = employeeDOS.stream().map(employee -> {
                EmployeeQueryVO employeeQueryVO = new EmployeeQueryVO();
                BeanUtils.copyProperties(employee, employeeQueryVO);
                Long deptId = employee.getDeptId();
                // 获取员工部门信息
                DepartmentDO departmentDO = departmentMapper.selectOne(new QueryWrapper<DepartmentDO>().eq("id", deptId));
                employeeQueryVO.setDepartmentDO(departmentDO);
                return employeeQueryVO;
            }).collect(Collectors.toList());

            // 多少页
            int totalPage;
            // 总记录数
            int totalRecords = employeeQueryVOS.size();
            if (employeeQueryVOS.size() % size == 0) {
                totalPage = totalRecords / size;
            } else {
                totalPage = totalRecords / size + 1;
            }
            // 当前数据 = (page-1)*
            List<EmployeeQueryVO> currentData = employeeQueryVOS.subList((page - 1) * size, Math.min(((page - 1) * size + size), totalRecords));

            /*map.put("total_page", totalPage);
            map.put("total_records", totalRecords);
            map.put("current_data", currentData);
            return map;*/
            voPageInfo.setPage(page);
            voPageInfo.setSize(size);
            voPageInfo.setTotalPage((long) totalPage);
            voPageInfo.setCurrentData(currentData);
            voPageInfo.setTotalRecords((long)totalRecords);
            return voPageInfo;
        }
        return null;
    }


    /**
     * 查找VO用户
     *
     * @param id
     * @return
     */
    @Override
    public EmployeeVO getVO(Long id) {

        EmployeeDO employeeDO = employeeMapper.selectOne(new QueryWrapper<EmployeeDO>().eq("id", id));
        if (employeeDO != null) {
            Long deptId = employeeDO.getDeptId();
            EmployeeVO employeeVO = new EmployeeVO();
            BeanUtils.copyProperties(employeeDO, employeeVO);

            // 查找部门信息
            DepartmentDO departmentDO = departmentMapper.selectOne(new QueryWrapper<DepartmentDO>().eq("id", deptId));
            employeeVO.setDepartmentDO(departmentDO);

            // 查找权限
            List<EmployeeRoleDO> employeeRoleDOS = employeeRoleMapper.selectList(new QueryWrapper<EmployeeRoleDO>().eq("employee_id", id));
            List<RoleDO> roleDOS = new ArrayList<>();
            for (EmployeeRoleDO employee : employeeRoleDOS) {
                roleDOS.add(roleMapper.selectOne(new QueryWrapper<RoleDO>().eq("id", employee.getRoleId())));
            }
            // 添加权限信息
            employeeVO.setRoleDOS(roleDOS);
            return employeeVO;
        }
        return null;
    }

    /**
     * 登录
     * @param username
     * @param password
     */
    @Override
    public void login(String username, String password) {
        EmployeeDO employeeDO = employeeMapper.selectOne(new QueryWrapper<EmployeeDO>().eq("name", username).eq("password", password));
        if (employeeDO != null){
            //说明登陆信息正确,将用户信息存到session中
            ServletRequestAttributes rqa = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            //共享当前用户
            //属性名 EMPLOYEE_IN_SESSION 参考 navbar.jsp页面中取值的属性名,两者要保持一致
            rqa.getRequest().getSession().setAttribute("EMPLOYEE_IN_SESSION",employeeDO);
            //如果登录的员工不是超级管理员
            if(!employeeDO.getAdmin()){
                //查询该员工拥有的权限
                List<String> permissions = permissionMapper.selectExpressionByEmpId(employeeDO.getId());
                rqa.getRequest().getSession().setAttribute("PERMISSION_IN_SESSION",permissions);
            }
        }else {
            throw new CustomException(-1,"账号或者密码错误");
        }

    }


    /**
     * 退出登录
     */
    @Override
    public void logout() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        servletRequestAttributes.getRequest().getSession().removeAttribute("EMPLOYEE_IN_SESSION");
        servletRequestAttributes.getRequest().getSession().removeAttribute("PERMISSION_IN_SESSION");
    }
}
